package pl.edu.mimuw.mas.agent.behaviour;

import java.util.Iterator;

import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DFUnregisterBehaviour extends OneShotBehaviour {
	
	private static final long serialVersionUID = -7639799975292459672L;

	private final Logger log = LoggerFactory.getLogger(getClass());

	private final String serviceType;

	public DFUnregisterBehaviour(Agent agent, String serviceType) {
		super(agent);
		this.serviceType = serviceType;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void action() {
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(myAgent.getAID());
		
		try {
			DFAgentDescription[] result;
			result = DFService.search(myAgent, dfd);
			dfd = result[0]; // mogę, bo skoro chce coś odrejestrować to musi być taki wpis
			Iterator<ServiceDescription> iter = dfd.getAllServices();
			ServiceDescription sd = null;
			ServiceDescription toDel = null;
			String services = "";
			while (iter.hasNext()) {
				sd = iter.next();
				if (sd.getName().equals(serviceType) && sd.getType().equals(serviceType)) {
					toDel = sd;
				} else {
					services = services.concat((services.length() == 0 ? "" : ", ") + sd.getName());
				}
			}
			if (toDel != null) {
				dfd.removeServices(sd);
				DFService.modify(myAgent, dfd);
				log.info("{} :  usługa {} usunięta z DF (pozostałe to <" + services + ">)",
						myAgent.getName(), serviceType);
			} else {
				log.info("{} : brak usługi o podanej nazwie (pozostałe to <{}>)",
						myAgent.getName(), services);
			}
			
		} catch (FIPAException e) {
			log.error("błąd jade", e);
		}
	}

}
